package com.web.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.web.pojo.User;
import com.web.service.UserService;

@Controller
public class UserController {
	@Autowired
	UserService UserService;
	//日志记录
	private Logger logger = LoggerFactory.getLogger(UserController.class);

	// 用户登入
	@RequestMapping(value = "usersLogin", method = RequestMethod.POST)
	public String usersLogin(String mailBox, String userPassword, HttpServletRequest request) {
		User users = UserService.UserGetByMailBoxAndPassword(mailBox, userPassword);
		if (users != null) {
			if ("管理员".equals(users.getRoleName())) {
				// 保存Session
				request.getSession().setAttribute("users", users);
				//打印日志
				logger.info("用户登入|登入成功|" + users.getUserName());
				return "adminlink";
			} else {
				// 保存Session
				request.getSession().setAttribute("users", users);
				//打印日志
				logger.info("用户登入|登入成功|" + users.getUserName());
				return "userlink";
			}
		}
		request.getSession().setAttribute("ret", "用户名或密码错误");
		logger.info("用户登入|密码错误|" + mailBox);
		return "login.jsp";
	}

	// 管理员登入跳转
	@RequestMapping("adminlink")
	public String loginLink() {
		return "index-admin.jsp";
	}

	// 用户登入跳转
	@RequestMapping("userlink")
	public String userlink() {
		return "index-user.jsp";
	}

	// 所有用户退出
	@RequestMapping("usersExit")
	public String usersExit(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("users");
		if (user != null) {
			request.getSession().removeAttribute("users");
			request.getSession().removeAttribute("ret");
			logger.info("用户退出|退出成功|" + user.getUserName());
			return "login.jsp";
		}
		request.getSession().removeAttribute("ret");
		return "login.jsp";
	}

	// 登入页面检查跳转管理员/用户页面
	@RequestMapping("usersCheck")
	public String usersCheck(HttpServletRequest request) {
		User user = (User) request.getSession().getAttribute("users");
		if (user != null) {
			if ("管理员".equals(user.getRoleName())) {
				return "adminlink";
			}
			return "userlink";
		}
		return "login.jsp";
	}

}
